﻿using System.Linq;
using PSE.Deployment.SetupBase;
using PSE.Deployment.SetupBase.Parameter.Enums;
using PSE.Deployment.SetupBase.UI;
using PSE.Deployment.SetupBase.UI.CustomComponents;
using PSE.Deployment.Util;
using PSEComponents.Deployment.Setup.Main;

namespace PSEComponents.Deployment.Setup.UI
{
    public partial class ComponentsSelection : BaseWizardWindow
    {
        public bool ShowWindow { get; set; }

        public ComponentsSelection()
        {
            this.InitializeComponent();

            SetAllowNext();

            treeview.CheckStateChanged += new GroupsTreeView.CheckedChangedEventHandler(treeview_CheckStateChanged);
            treeview.CheckStateChanging += new GroupsTreeView.CheckedChangingEventHandler(treeview_CheckStateChanging);

            ShowWindow = treeview.Groups.Count() > 1;
        }

        private void treeview_CheckStateChanged(object sender, CheckedChangedEventArgs e)
        {
            SetAllowNext();
        }

        private void treeview_CheckStateChanging(object sender, CheckedChangingEventArgs e)
        {
            if (sender is TreeViewModel)
            {
                TreeViewModel tvm = (TreeViewModel)sender;

                EnableDependency(e, tvm, "PSEComponents-ProcessManager-Server", "PSEComponents-ProcessManager-Client");
                EnableDependency(e, tvm, "PSEComponents-Hoster", "PSEComponents-Hoster-Client");
                EnableDependency(e, tvm, "PSEComponents-LogPackager-Server", "PSEComponents-LogPackager-Client");
                EnableDependency(e, tvm, "PSEComponents-Updater-Server", "PSEComponents-Updater-Client");
            }
        }

        private void EnableDependency(CheckedChangingEventArgs e, TreeViewModel tvm, string parentNode, string childNode)
        {
            if (tvm.Id.Equals(parentNode) && (e.IsChecked == null || e.IsChecked.GetValueOrDefault()))
            {
                TreeViewModel client = treeview.TreeViewModels.SelectDeep(t => t.Children).Single(m => m.Id == childNode);
                if (client != null)
                    client.IsChecked = true;
            }
            else if (tvm.Id.Equals(childNode))
            {
                TreeViewModel sm = treeview.TreeViewModels.SelectDeep(t => t.Children).Single(m => m.Id == parentNode);
                e.Cancel = (sm != null && (sm.IsChecked == null || sm.IsChecked.GetValueOrDefault()));
            }
        }

        private void SetAllowNext()
        {
            this.AllowNext = treeview.Groups.Any(g => (g.Install == null || g.Install.GetValueOrDefault()) && !g.Installed) ||
                             treeview.Groups.Any(g => (g.Install.HasValue && !g.Install.Value) && g.Installed);
        }
    }
}